﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MySql;
using MySql.Data;
using MySql.Data.MySqlClient;
using MySql.Data.Entity;
using ASV.Classes;
using System.Data;

namespace ASV.Classes
{
    public class Authentication
    {
        private MySql.Data.MySqlClient.MySqlConnection connection;
        public bool loginStatus;

        public Authentication()
        {
        }

        public Authentication(MySql.Data.MySqlClient.MySqlConnection connection)
        {
            this.connection = connection;
        }

        public bool successfulLoggedIn()
        {
            if (this.loginStatus == true)
            {
                return true;
            }
            return false;
        }

        public bool login(string username, string password)
        {
            MySqlCommand selectUser = new MySqlCommand();
            string SQL = "SELECT * FROM benutzer WHERE kundennummer = '" + username + "' AND passwort = '" + password + "'";
            selectUser.CommandText = SQL;
            selectUser.Connection = this.connection;

            MySqlDataAdapter adapter = new MySqlDataAdapter(selectUser);
            MySqlDataReader reader = selectUser.ExecuteReader();

            if (reader.HasRows != false)
            {
                while (reader.Read())
                {
                    HttpContext.Current.Session["kundennummer"] = reader["kundennummer"].ToString();
                    HttpContext.Current.Session["vorname"] = reader["vorname"].ToString();
                    HttpContext.Current.Session["nachname"] = reader["nachname"].ToString();
                    HttpContext.Current.Session["email"] = reader["email"].ToString();
                    HttpContext.Current.Session["benutzertyp"] = reader["benutzertyp"].ToString();
                    HttpContext.Current.Session["isLoggedIn"] = "true";
                }
                return true;
            }
            return false;
        }

        public void logout()
        {
            HttpContext.Current.Session.Abandon();
        }

        public bool isLoggedIn()
        {
            if (HttpContext.Current.Session["isLoggedIn"] == null)
            {
                return false;
            }
            else if (HttpContext.Current.Session["isLoggedIn"].ToString() == "true")
            {
                return true;
            }
            return false;
        }

        public bool checkUserGroup(int userGroup, int allowedGroup)
        {
            if (userGroup >= allowedGroup)
            {
                return true;
            }
            return false;
        }
    }
}